document.addEventListener('DOMContentLoaded', function() {
    const searchForm = document.getElementById('searchForm');
    const loadingSpinner = document.getElementById('loadingSpinner');
    const resultsContainer = document.getElementById('resultsContainer');
    const platformResults = document.getElementById('platformResults');

    searchForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const brand = document.getElementById('brand').value.trim();
        const sku = document.getElementById('sku').value.trim();
        
        if (!brand || !sku) {
            alert('请填写完整的品牌和货号信息');
            return;
        }

        // 显示加载状态
        loadingSpinner.classList.remove('d-none');
        resultsContainer.classList.add('d-none');
        platformResults.innerHTML = '';

        try {
            const response = await fetch('/api/search', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ brand, sku })
            });

            const data = await response.json();
            
            if (data.success) {
                displayResults(data.data);
            } else {
                alert(data.message || '搜索失败，请重试');
            }
        } catch (error) {
            console.error('Error:', error);
            alert('网络错误，请检查网络连接后重试');
        } finally {
            loadingSpinner.classList.add('d-none');
        }
    });

    function displayResults(data) {
        // 更新价格统计
        document.getElementById('minPrice').textContent = `¥${data.priceRange.min}`;
        document.getElementById('maxPrice').textContent = `¥${data.priceRange.max}`;
        document.getElementById('avgPrice').textContent = `¥${data.priceRange.avg}`;
        document.getElementById('suggestPrice').textContent = `¥${data.suggestedPrice}`;

        // 清空并重新填充平台结果
        platformResults.innerHTML = '';
        
        data.platforms.forEach(platform => {
            const platformCard = createPlatformCard(platform);
            platformResults.appendChild(platformCard);
        });

        resultsContainer.classList.remove('d-none');
    }

    function createPlatformCard(platform) {
        const col = document.createElement('div');
        col.className = 'col-lg-4 mb-4';
        
        const card = document.createElement('div');
        card.className = 'card h-100 shadow';
        
        let platformLogo = '';
        let platformColor = '';
        
        switch(platform.name.toLowerCase()) {
            case 'jd':
                platformLogo = 'https://img10.360buyimg.com/img/jfs/t1/113724/17/36603/1826/63b6c808F8b54b6c7/7eb9a2166bf584d2.png';
                platformColor = 'danger';
                break;
            case 'taobao':
                platformLogo = 'https://img.alicdn.com/tfs/TB1pDDmmF67gK0jSZFHXXa9jVXa-234-120.png';
                platformColor = 'warning';
                break;
            case 'dewu':
                platformLogo = 'https://static.dewu.com/images/logo.png';
                platformColor = 'info';
                break;
        }

        const bestSeller = platform.products.find(p => p.isBestSeller);
        
        card.innerHTML = `
            <div class="card-header bg-${platformColor} text-white">
                <div class="d-flex align-items-center">
                    <img src="${platformLogo}" alt="${platform.name}" class="platform-logo me-2">
                    <h5 class="mb-0">${platform.displayName}</h5>
                </div>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <h6 class="text-muted">价格区间</h6>
                    <div class="d-flex justify-content-between">
                        <span class="text-success fw-bold">¥${platform.priceRange.min}</span>
                        <span class="text-muted">-</span>
                        <span class="text-danger fw-bold">¥${platform.priceRange.max}</span>
                    </div>
                </div>
                
                ${bestSeller ? `
                <div class="border rounded p-3 bg-light">
                    <h6 class="text-muted mb-2">
                        <i class="fas fa-crown text-warning me-1"></i>销量冠军
                    </h6>
                    <img src="${bestSeller.image}" alt="${bestSeller.title}" class="product-image mb-2">
                    <h6 class="mb-1">${bestSeller.title}</h6>
                    <div class="d-flex justify-content-between align-items-center">
                        <span class="h5 text-primary mb-0">¥${bestSeller.price}</span>
                        <span class="sales-info">销量: ${bestSeller.sales}</span>
                    </div>
                </div>
                ` : '<p class="text-muted">暂无商品数据</p>'}
            </div>
        `;
        
        col.appendChild(card);
        return col;
    }
});
